package cn.donting.jme.expansion.tool;

import cn.donting.jme.EditorContent;
import cn.donting.jme.editor.scene.Scene;
import cn.donting.jme.editor.scene.SceneCamera;
import com.jme3.collision.CollisionResults;
import com.jme3.input.InputManager;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;

import javax.swing.*;

/**
 * 场景编辑工具
 */
public abstract class AbsSceneTool implements SceneTool {
    private Spatial selectSpatial;
    private SceneCamera selectCamera;
    private Node toolNode;
    private boolean active;

    public AbsSceneTool() {
        this.toolNode = new Node("toolNode-" + getName());
    }

    public Node getToolNode() {
        return toolNode;
    }

    public void active(boolean active) {
        this.active = active;
    }

    public Spatial getSelectSpatial() {
        return this.selectSpatial;
    }

    @Override
    public void setSelectSpatial(Spatial selectSpatial) {
        this.selectSpatial = selectSpatial;
        this.selectCamera = null;
    }


    @Override
    public void setSelectCamera(SceneCamera sceneCamera) {
        this.selectSpatial = null;
        this.selectCamera = sceneCamera;
    }

    @Override
    public SceneCamera getSelectCamera() {
        return selectCamera;
    }

    /**
     * 鼠标拾取
     * @return
     */
    public CollisionResults getMouseSelectGeometry(Spatial spatial) {
        CollisionResults results = new CollisionResults();
        Camera camera = EditorContent.getJmeApplication().getEditorCamera();
        InputManager inputManager = EditorContent.getJmeApplication().getInputManager();
        Vector2f cursorPosition = inputManager.getCursorPosition();
        Vector3f worldCoordinates = camera.getWorldCoordinates(cursorPosition, 1);
        //计算视线方向
        Vector3f dir = worldCoordinates.subtract(camera.getLocation());
        dir.normalizeLocal();
        Ray ray = new Ray(camera.getLocation(), dir);
        ray.setLimit(100);
        spatial.collideWith(ray, results);
        return results;
    }



}
